package com.pms.web;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.rpc.IMemberService;
import com.pms.service.*;
import com.pms.util.FluoriteCloudUtile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.pms.controller.BaseController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("estateEqCamera")
@Api(value="物业设备摄像头",description = "物业设备摄像头")
public class EstateEqCameraController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IEstateEqCameraService estateEqCameraService;
    @Autowired
    IUnitBuildingService unitBuildingService;
    @Autowired
    IEntranceDoorService entranceDoorService;
    @Autowired
    IEstateAgencyService agencyService;
    @Autowired
    public ICameraUserInformationService service;
    @Autowired
    IMemberService memberService;
    /**
     * 分页查询摄像头
     * @param limit
     * @param page
     * @return
     */
    @ApiOperation(value = "分页查询摄像头")
    @RequestMapping(value = "/page",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="limit",value="条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="place",value="摄像头位置",required = false,dataType = "String",paramType="form")
    })
    public R page(int limit, int page,String place){
        if(limit<1){limit=10;}
        if(page<1){page=1;}
        Page<EstateEqCamera> pages = new Page<EstateEqCamera>(page,limit);
        pages = estateEqCameraService.selectPage(pages,new EntityWrapper<EstateEqCamera>().like("place_",place));
        return R.ok().put("data",pages).putDescription(EstateEqCamera.class);
    }

    /**
     * 新增
     * @param place
     * @param key
     * @param remack
     * @param agencyId
     * @param verificationCode
     * @param memberId
     * @param communityId
     * @param privilegedStatus
     * @return
     */
    @ApiOperation(value = "添加摄像头")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="place",value="摄像头位置",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="key",value="设备序列号",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="remack",value="备注",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区ID",required = false,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="privilegedStatus",value="权限状态1公开、2小区所见、3私人所见",required = true,dataType = "Integer",paramType="form"),
            @ApiImplicitParam(name="verificationCode",value="验证码",required = false,dataType = "String",paramType="form"),
            })
    public R add(String place,String key,String remack,Long agencyId,String verificationCode,Long memberId,Long communityId,Integer privilegedStatus){
        parameterIsBlank(place,"设备序列号不能为空");
        parameterIsBlank(key,"设备序列号不能为空");
        parameterIsNull(memberId,"会员ID不能为空");
        parameterIsBlank(verificationCode,"设备验证码不能为空");
        EstateEqCamera entity =new EstateEqCamera();
        CameraUserInformation cu= new CameraUserInformation();
        if(null==privilegedStatus && privilegedStatus==0){
            return R.error(400,"权限状态不能为空");
        }else if (privilegedStatus.equals(1)){//1公开
            if(StringUtils.isEmpty(agencyId.toString())){return R.error(400,"机构ID不能为空");}
            EstateAgency agency = agencyService.selectById(agencyId);
            if(null==agency){return R.error(400,"该机构信息不存在"); }
            if(agency.getAgencyState()==2){return R.error(400,"该机构已被停用，请联系相关管理员"); }
            entity.setAgencyId(agencyId);
        }else if (privilegedStatus.equals(2)){//2小区所见
            if(StringUtils.isEmpty(communityId.toString())){return R.error(400,"社区ID不能为空"); }
            EstateAgency agency = agencyService.selectById(agencyId);
            if(null==agency){return R.error(400,"该社区机构信息不存在"); }
            if(agency.getAgencyState()==2){return R.error(400,"该社区机构已被停用，请联系相关管理员"); }
            entity.setCommunityId(communityId);
        }else if (privilegedStatus.equals(3)){//3私人所见
        }else{
            return R.error(400,"权限设置状态信息不正确，请重新输入");
        }
        MemberInfo sysMember=memberService.queryBymember(memberId);
        if(sysMember==null){ return R.error(400,"该会员memberId信息不存在"); }
        entity.setMemberId(memberId);
        entity.setKey(key);//序列号
        entity.setPrivilegedStatus(privilegedStatus);//权限状态
        entity.setVerificationCode(verificationCode);//验证码
        entity.setPlace(place);//位置
        entity.setRemack(place);//备注
        entity.setEquipmentId("1");//通道号默认为1
        entity.setCreateTime(new Date());//创建时间
        entity.setCurrentdateTime(new Date());//当前时间
        List<CameraUserInformation> user = service.selectList(new EntityWrapper<CameraUserInformation>().lt("sum_",10));//查询所有摄像头sum不足10个
        if(null!=user ||!user.isEmpty()){
            entity.setCameraUserId(user.get(0).getId());
            cu=service.selectById(user.get(0).getId());
            JSONObject json = null;
            try {
                json = FluoriteCloudUtile.fluoriteCloud1(cu.getAppkey(),cu.getAppsecret());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(json.getString("code").equals("200")){
                String data = json.getString("data");
                if(StringUtils.isNotEmpty(data)){
                    JSONObject jsonResult = JSON.parseObject(data);
                    String accessToken = jsonResult.getString("accessToken");//token码
                    String expireTime = jsonResult.getString("expireTime");//结束时间
                    entity.setToken(accessToken);//保存token码
                    try{
                        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Long time=new Long(expireTime);
                        String d = format.format(time);//时间戳转换成标准时间
                        Date  e = format.parse(d);     //标准时间转换成国际时间
                        Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历
                        cal.setTime(e);
                        cal.add(Calendar.DATE, -1);  //结束时间减1天
                        entity.setExpireTime(format.parse(format.format(cal.getTime())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }else{
                return R.error(400,json.toJSONString());
            }
            JSONObject cloud =new JSONObject();
            try {
                cloud = FluoriteCloudUtile.addfluoriteCloud(entity.getKey(), entity.getVerificationCode(),entity.getToken());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if(cloud.getString("code").equals("200")){
                estateEqCameraService.insert(entity);
                cu.setSum(cu.getSum()+1);
                service.updateAllColumnById(cu);//修改总数
                return R.ok();
            }else{
                return R.error(400,cloud.toJSONString());
            }
        }else {
            return R.error(400,"对不起没有可用用户配置信息，请联系管理员");
        }
    }

    /**
     * 修改摄像头信息
     * @param place
     * @param key
     * @param remack
     * @param verificationCode
     * @param cameraId
     * @return
     */
    @ApiOperation(value = "修改摄像头信息")
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="cameraId",value="摄像头ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="place",value="摄像头位置",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="key",value="设备序列号",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="remack",value="备注",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="verificationCode",value="验证码",required = false,dataType = "String",paramType="form"),
    })
    public R update(String place,String key,String remack,String verificationCode,Long cameraId) {
        parameterIsBlank("cameraId","摄像头设备ID不能为空");
        EstateEqCamera eq=estateEqCameraService.selectById(cameraId);//判断摄像头是否存在
        parameterIsBlank("eq","该设备信息不存在，请从新输入");
        if (!StringUtils.isEmpty(key)){//是否修改设备序列号
            eq.setKey(key);
        }
        if (!StringUtils.isEmpty(verificationCode)){//是否修改验证码
            eq.setVerificationCode(verificationCode);
        }
        if (!StringUtils.isEmpty(remack)){//是否修改备注
            eq.setRemack(remack);
        }
        if (!StringUtils.isEmpty(place)){//是否修改位置
            eq.setPlace(place);
        }
        estateEqCameraService.updateById(eq);
        return R.ok();
    }
        /**
         * 删除摄像头
         * @param cameraId
         * @param memberId
         * @return
         */
    @ApiOperation(value = "删除摄像头")
    @RequestMapping(value = "/deldete/camera")
    @ApiImplicitParams({
        @ApiImplicitParam(name="memberId",value="会员ID",required = true,dataType = "Long",paramType="form"),
        @ApiImplicitParam(name="cameraId",value="摄像头ID",required = true,dataType = "Long",paramType="form"),
    })
    public Object deldeteCamera(Long cameraId,Long memberId){
        parameterIsNull(cameraId,"该摄像头ID不能为空");
        parameterIsNull(memberId,"该会员ID不能为空");
        EstateEqCamera eqCamera=estateEqCameraService.selectById(cameraId);
        if(eqCamera==null){return R.error(400,"该摄像头信息不存在");}
        if(StringUtils.isEmpty(eqCamera.getMemberId().toString())){return R.error(400,"该摄像头会员信息不存在");}
        if(eqCamera.getMemberId().equals(memberId)){
            CameraUserInformation user=service.selectById(eqCamera.getCameraUserId());
            if(user==null){return R.error(400,"该摄像头用户信息不存在");}
            if (user.getSum()==0||user.getSum()>10) {return R.error(400,"该摄像头用户总数异常");}
            JSONObject cloud=FluoriteCloudUtile.deletefluoriteCloud(eqCamera.getKey(),eqCamera.getToken());
            if(cloud.getString("code").equals("200")){
                user.setSum(user.getSum()-1);
                service.updateAllColumnById(user);
                estateEqCameraService.deleteById(eqCamera.getCameraId());
                return R.ok();
            }else{
                return R.error(400,cloud.toJSONString());
            }
        }else{
            return R.error(400,"你没有权限删除不属于自己的摄像头信息");
        }
    }

    /**
     * 修改摄像头权限
     * @param memberId
     * @param cameraId
     * @param privilegedStatus
     * @param agencyId
     * @param communityId
     * @return
     */
    @ApiOperation(value = "修改摄像头权限")
    @RequestMapping(value = "/update/status")
    @ApiImplicitParams({
            @ApiImplicitParam(name="cameraId",value="摄像头ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="privilegedStatus",value="权限状态1公开、2小区所见、3私人所见",required = true,dataType = "Integer",paramType="form"),
    })
    public Object updateStatus(Long memberId, Long cameraId,Integer privilegedStatus,Long agencyId,Long communityId){
        parameterIsNull(cameraId,"该摄像头ID不能为空");
        parameterIsNull(memberId,"该会员ID不能为空");
        EstateEqCamera eqCamera=estateEqCameraService.selectById(cameraId);
        if(eqCamera==null){return R.error(400,"该摄像头信息不存在");}
        if(StringUtils.isEmpty(eqCamera.getMemberId().toString())){return R.error(400,"该摄像头会员信息不存在");}
        if(eqCamera.getMemberId().equals(memberId)){
            if(StringUtils.isEmpty(privilegedStatus.toString())){
                return R.error(400,"权限设置privilegedStatus不能为空");
            }else if (privilegedStatus.equals(1)){//1公开
                if(StringUtils.isEmpty(agencyId.toString())){return R.error(400,"物业机构spId不能为空");}
                EstateAgency agency = agencyService.selectById(agencyId);
                if(null==agency){return R.error(400,"该机构信息不存在"); }
                if(agency.getAgencyState()==2){return R.error(400,"该机构已被停用，请联系相关管理员"); }
                eqCamera.setPrivilegedStatus(privilegedStatus);
                eqCamera.setAgencyId(agencyId);
            }else if (privilegedStatus.equals(2)){//2小区所见
                if(StringUtils.isEmpty(communityId.toString())){return R.error(400,"社区机构communityId不能为空");}
                EstateAgency agency = agencyService.selectById(agencyId);
                if(null==agency){return R.error(400,"该社区机构信息不存在"); }
                if(agency.getAgencyState()==2){return R.error(400,"该社区机构已被停用，请联系相关管理员"); }
                eqCamera.setPrivilegedStatus(privilegedStatus);
                eqCamera.setCommunityId(communityId);
            }else if (privilegedStatus.equals(3)){//3私人所见
                if(StringUtils.isEmpty(memberId.toString())){return R.error(400,"会员memberId不能为空");}
                MemberInfo sysMember=memberService.queryBymember(memberId);
                if(sysMember==null){ return R.error(400,"该会员memberId信息不存在"); }
                eqCamera.setPrivilegedStatus(privilegedStatus);
                eqCamera.setMemberId(memberId);
            }else{return R.error(400,"权限设置状态信息不正确，请重新输入");}
            estateEqCameraService.updateAllColumnById(eqCamera);
            return R.ok().put("data",eqCamera);
        }else{return R.error(400,"你不能修改不属于自己的摄像头信息");}
    }


    /**
     * 分页查询摄像头列表
     * @param pageSize
     * @param pageNum
     * @param memberId
     * @param privilegedStatus
     * @param agencyId
     * @param communityId
     * @return
     */
    @ApiOperation(value = "分页查询摄像头列表")
    @RequestMapping(value = "/page/camera")
    @ApiImplicitParams({
            @ApiImplicitParam(name="pageSize",value="条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="agencyId",value="机构ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="memberId",value="会员ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="communityId",value="社区ID",required = true,dataType = "Long",paramType="form"),
            @ApiImplicitParam(name="privilegedStatus",value="权限状态1公开、2小区所见、3私人所见",required = true,dataType = "Integer",paramType="form"),
    })
    public Object pageCamera(Integer pageSize,Integer pageNum,Long memberId,Integer privilegedStatus,Long agencyId,Long communityId){
       if(pageSize<1){pageSize=10;}
        if(pageNum<1){pageSize=1;}
        Page<EstateEqCamera> arrPage=null;
        if(privilegedStatus<1){
            return R.error(400,"权限设置privilegedStatus不能为空");
        }else if (privilegedStatus.equals(1)){//1公开
            if(StringUtils.isEmpty(agencyId.toString())){return R.error(400,"物业机构agencyId不能为空");}
            EstateAgency agency = agencyService.selectById(agencyId);
            if(null==agency){return R.error(400,"该机构信息不存在"); }
            if(agency.getAgencyState()==2){return R.error(400,"该机构已被停用，请联系相关管理员"); }
            Wrapper<EstateEqCamera> wrapper =new EntityWrapper<EstateEqCamera>().eq("privileged_status",privilegedStatus);
            wrapper.eq("agency_id",agencyId);
            arrPage =estateEqCameraService.selectPage(new Page<EstateEqCamera>(pageNum,pageSize),wrapper);
        }else if (privilegedStatus.equals(2)){//2小区所见
            if(StringUtils.isEmpty( communityId.toString())){return R.error(400,"社区机构communityId不能为空");}
            EstateAgency agency = agencyService.selectById(agencyId);
            if(null==agency){return R.error(400,"该社区机构信息不存在"); }
            if(agency.getAgencyState()==2){return R.error(400,"该机构已被停用，请联系相关管理员"); }
            Wrapper<EstateEqCamera> wrapper =new EntityWrapper<EstateEqCamera>().eq("privileged_status",privilegedStatus);
            wrapper.eq("community_id",communityId);
            arrPage =estateEqCameraService.selectPage(new Page<EstateEqCamera>(pageNum,pageSize),wrapper);
        }else if (privilegedStatus.equals(3)){//3私人所见
            if(StringUtils.isEmpty(memberId.toString())){return R.error(400,"会员memberId不能为空");}
            MemberInfo sysMember=memberService.queryBymember(memberId);
            if(sysMember==null){return R.error(400,"该会员memberId信息不存在");}
            Wrapper<EstateEqCamera> wrapper =new EntityWrapper<EstateEqCamera>().eq("privileged_status",privilegedStatus);
            wrapper.eq("member_id",memberId);
            arrPage =estateEqCameraService.selectPage(new Page<EstateEqCamera>(pageNum,pageSize),wrapper);
        }else if(privilegedStatus.equals(100)){//状态为100查询全部
//            Wrapper<EstateEqCamera> wrapper =new EntityWrapper<EstateEqCamera>().eq("privileged_status",1);
//            wrapper.eq("agency_id",agencyId).eq("member_id",memberId);
//            if (communityId!=null){
//                wrapper.eq("community_id",communityId).eq("privileged_status",2);
//            }
//            arrPage =estateEqCameraService.selectPage(new Page<EstateEqCamera>(pageNum,pageSize),wrapper);
        }else{return R.error(400,"权限设置状态信息不正确，请重新输入");}
        return R.ok().put("data",arrPage).putDescription(EstateEqCamera.class);
    }




}